const adapters = require("../../utils/adapters");
const app = getApp()
Page({
  data: {
    header: {
      title: '长兴诺力售后',
      whiteBg: false,
      mode: 'title',
      navBarHeight: app.globalData.navBarHeight
    },

    tarBarActive: 0,
    pageMode: 0, // 0提交，1编辑
    isPoup: false,
    userInfo: null, // 用户个人信息
    
    activeFaultUnite: null, // 故障原因悬浮窗激活状态

    queryGroup: {
      battery: '',

      manuallyInputVisible: false, // 控制悬浮输入框的显示/隐藏
    },

    workOrder: {
      number: '',
      batteryList: [],
      failureCauseList: [],
      userAfterSaleMethod: '',
      userPostDescription: '',
      userPostPhotoList: [],
      manufacturerList: [{manufacturer: '暂无数据', userSelected: true}],
      batteryModel: '暂无数据',
    },
    postTypeList: [
      { activeSrc: '../../image/change_new_active.png', inactiveSrc: '../../image/change_new.png', comment: '换新' },
      { activeSrc: '../../image/turnover_active.png', inactiveSrc: '../../image/turnover.png', comment: '周转' },
      { activeSrc: '../../image/repair_active.png', inactiveSrc: '../../image/repair.png', comment: '维护' },
      { activeSrc: '../../image/scrap_active.png', inactiveSrc: '../../image/scrap.png', comment: '报废' }
    ], // 售后申请类型图片按钮
  },
  tarBarChange() {
    this.setData({tarBarActive: 0})
  },
  async onLoad(option) {
    this.setData({
      userInfo: wx.getStorageSync('userInfo'),
    });
    console.log(option)
    if (option.pagemode !== null && option.pagemode !== undefined) {
      this.setData({
        pageMode: Number(option.pagemode),
        'workOrder.number': option.maintenancenumber,
        'header.mode': 'back',
      });

      const result = await adapters.getMaintenanceDetail({
        type: 1,
        phoneNumber: this.data.userInfo.phoneNumber,
        workOrderNumber: option.maintenancenumber
      });
      console.log(result)
      if (result.success) {
        this.setData({ workOrder: result.data });
      } else {
        wx.showToast({ title: result.message, icon: 'none' });
      }
    }
  },

  onPageScroll(e) {
    this.setData({
      'header.whiteBg': e.scrollTop < 40 ? false : true
    })
  },

  closeBox() {
    this.setData({
      isPoup: false
    })
  },

  // 手输编号 输入框 显隐状态变更
  openManuallyInput() {
    this.setData({
      'queryGroup.manuallyInputVisible': true,
    });
  },

  closeManuallyInput() {
    this.setData({
      'queryGroup.manuallyInputVisible': false,
    });
  },

  // 手动输入电池编号
  manuallyInputBatteryNumber(e) {
    this.setData({
      'queryGroup.battery': e.detail.value
    });
  },
  // 扫码输入电池编号
  scanCodeInputBatteryNumber() {
    wx.scanCode({
      success: (res) => { 
        console.log('扫描结果:', res.result);
        this.refreshPage();
        this.setData({ 
          'queryGroup.battery': res.result,
        });
        this.queryPage();
      },
      fail: (err) => {
        console.log('扫码失败:', err);
        wx.showToast({
          title: '扫码失败，请重试',
          icon: 'none',
        })
      }
    })
  },

  // 确认查询
  queryPage() {
    const batteryNumber = this.data.queryGroup.battery;
    const userInfo = this.data.userInfo
    this.refreshPage();
    if (batteryNumber) {
      adapters.getMaintenanceDetail({type: 0, phoneNumber: userInfo.phoneNumber, batteryNumber: batteryNumber})
      .then(res => {
        if(res.success){
          this.setData({
            workOrder: res.data,
            'queryGroup.battery': batteryNumber,
          })
        } else {
          wx.showToast({
            title: res.message,
            icon: 'none'
          })
        }
      })
    } else {
      wx.showToast({
        title: '请输入有效内容',
        icon: 'none'
      });
    }
  },


  // 电池checked变更
  uniteCheckStatusChange(e) {
    const index = e.currentTarget.dataset.index;
    const userSelected = this.data.workOrder.batteryList[index].userSelected
    let newData = {};
    if ( userSelected === false || userSelected === true) {
      newData[`workOrder.batteryList[${index}].userSelected`] = !userSelected;
      if(userSelected) {this.resetFailureCauseBatterySelected(index);}
      this.setData(newData);
      const allChecked = this.data.workOrder.batteryList.every(item => item.userSelected === true);
      if (allChecked) {
        this.data.workOrder.batteryList.forEach((_, i) => {
          newData[`workOrder.batteryList[${i}].userSelected`] = 'allTrue';
        });
      }
    } else {
      this.data.workOrder.batteryList.forEach((item, i) => {
        newData[`workOrder.batteryList[${i}].userSelected`] = true;
      });
      newData[`workOrder.batteryList[${index}].userSelected`] = false;
      this.resetFailureCauseBatterySelected(index);
    }
    this.setData(newData);
  },

  // 电池全选checked变更
  uniteAllCheckStatusChange() {
    if (this.data.workOrder.batteryList.length === 0) {
      wx.showToast({
        title: '请先输入电池编号',
        icon: 'none'
      })
      return
    }
    let newData = {};
    if (this.data.workOrder.batteryList[0].userSelected === 'allTrue') {
      this.data.workOrder.batteryList.forEach((item, i) => {
        this.resetFailureCauseBatterySelected(i);
        newData[`workOrder.batteryList[${i}].userSelected`] = false;
      });
    } else {
      this.data.workOrder.batteryList.forEach((item, i) => {
        newData[`workOrder.batteryList[${i}].userSelected`] = 'allTrue';
      });
    }
    this.setData(newData);
  },

  // 故障原因checked变更
  faultCheckStatusChange(e) {
    const faultIndex = e.currentTarget.dataset.index;
    const failureCause = this.data.workOrder.failureCauseList[faultIndex]
    let newData = {};
    const selectPermission = this.data.workOrder.batteryList.find(item => item.userSelected || item.userSelected === 'allTrue')
    if (!selectPermission) {
      wx.showToast({
        title: '请选择退回电池组！',
        icon: 'none'
      })
      newData[`workOrder.failureCauseList[${faultIndex}].userSelected`] = failureCause.userSelected;
      this.setData(newData);
      return
    } else {
      newData[`workOrder.failureCauseList[${faultIndex}].userSelected`] = !failureCause.userSelected;
      this.setData(newData);
    }
    if (failureCause.userSelected && failureCause.multipleSelections) {
      this.openFaultUniteCheck(faultIndex)
    }
  },



  resetFailureCauseBatterySelected(batteryIndex) {
    const failureCauseList = this.data.workOrder.failureCauseList
    failureCauseList.forEach(failureCause => {
      failureCause.batteryList.forEach((item, index) => {
        item.userSelected = index === batteryIndex ? false : item.userSelected
      })
    })
    this.setData({
      'workOrder.failureCauseList': failureCauseList
    })
  },

  // 故障原因电池checked变更
  faultUniteCheckStatusChange(e) {
    const faultIndex = e.currentTarget.dataset.faultindex;
    const faultUnitIndex = e.currentTarget.dataset.faultuniteindex;
    let newData = {};
    newData[`workOrder.failureCauseList[${faultIndex}].batteryList[${faultUnitIndex}].userSelected`] = !this.data.workOrder.failureCauseList[faultIndex].batteryList[faultUnitIndex].userSelected;
    this.setData(newData);
  },

  // 打开 故障原因电池编号悬浮窗
  openFaultUniteCheck(e) {
    let index = null;
    if (typeof(e) === 'number') {
      index = e
    }else {
      index = e.currentTarget.dataset.index
    }
    let checkNum = 0;
    this.data.workOrder.batteryList.forEach((item, i) => {
      if (item.userSelected || item.userSelected === 'allTrue') {
        checkNum += 1
      }
    });
    if (checkNum === 0) {
      wx.showToast({
        title: '请选择退回电池组！',
        icon: 'none'
      })
      return
    }
    this.setData({
      activeFaultUnite: index
    });
  },

  // 关闭故障原因下 电池子编号悬浮窗
  closeFaultUniteCheck() {
    this.setData({
      activeFaultUnite: null
    })
  },

  // 申请类型切换
  postTypeChange(e) {
    const comment = e.currentTarget.dataset.comment;
    this.setData({
      [`workOrder.userAfterSaleMethod`]: comment
    })
  },

  // 故障描述更新
  faultDescriptionChange(e) {
    this.setData({
      'workOrder.userPostDescription': e.detail.value
    });
  },

  // 选择图片
  chooseImage(event) {
    const { file } = event.detail;
    const index = event.detail.index;
    console.log("用户添加了图片" + index)
    let imageList = this.data.workOrder.userPostPhotoList
    if(index !== undefined && index !== null) {
      imageList.push({ url: file.url, key: '' });
    }
    this.setData({
      'workOrder.userPostPhotoList': imageList
    })
  },
  // 移除图片
  removeImage(event) {
    const index = event.detail.index;
    console.log("用户移除了图片" + index)
    let imageList = this.data.workOrder.userPostPhotoList
    imageList.splice(index, 1);
    this.setData({
      'workOrder.userPostPhotoList': imageList
    })
  },

  // 仓商变更
  facturerSelectStatusChange(e) {
    console.log(e)
    const index = e.detail.value
    let manufacturerList = this.data.workOrder.manufacturerList
    manufacturerList.forEach(item => {
      item.userSelected = false;
    });
    manufacturerList[index].userSelected = true
    this.setData({
      'workOrder.manufacturerList': manufacturerList
    })
  },

  // 提交
  submit() {
    let { workOrder, userInfo } = this.data;

    // 提交前进行数据有效性验证
    if (!workOrder.batteryList.some(unit => unit.userSelected || unit.userSelected === 'allTrue')) {
      wx.showToast({
        title: '请选择退回设备组',
        icon: 'none',
      });
      return;
    };
    if (!workOrder.failureCauseList.some(unit => unit.userSelected === true)) {
      wx.showToast({
        title: '请选择故障原因',
        icon: 'none',
      });
      return;
    };
    if (workOrder.userAfterSaleMethod.length === 0) {
      wx.showToast({
        title: '请选择申请类型',
        icon: 'none',
      });
      return;
    };

    workOrder.userPhoneNumber = userInfo.phoneNumber
    workOrder.userName = userInfo.userName
    adapters.postMaintenanceDetail({ type: this.data.pageMode, workOrder: workOrder})
    .then((res) => {
      if(res.success) {
        this.setData({
          isPoup: true
        })
      } else {
        wx.showToast({ title: '提交失败：' + res.message, icon: 'none' });
      }
      if(this.data.pageMode === 0) {
        console.log(this.data.pageMode)
        this.refreshPage();
      }
    })
    .catch(error => {
      wx.showToast({ title: '提交失败：' + error, icon: 'none' });
      console.error('提交失败:', error);
    });
  },

  refreshPage() {
    this.setData({
      workOrder: {
        number: '',
        batteryList: [],
        failureCauseList: [],
        userAfterSaleMethod: '',
        userPostDescription: '',
        userPostPhotoList: [],
        manufacturerList: [{manufacturer: '暂无数据', userSelected: true}],
        batteryModel: '暂无数据',
      },
      queryGroup: {
        battery: '',

        manuallyInputVisible: false,
      },
    })
  },

});
 